﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Linq;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Dimok.Data.DataSources;
using Dimok.Web.UI;

public partial class Controls_VantageBridge : TableControl {
	Dimok.User.UserObject uox = new Dimok.User.UserObject();
	protected string ApplID { get { return Request["ApplID"] + ""; } }
	protected string Filter { 
		get {
			if (ApplID != "" && Request["Filter"] + "" != "") throw new NotSupportedException("ApplID and Filter should not be used together.");
			return ApplID == "" ? Request["Filter"] + "" : "ApplID=" + ApplID;
		} 
	}
	protected string UserName = Dimok.User.UserObject.CurrentUserName;
	protected string UserDomain = Dimok.User.UserObject.CurrentUserDomain;
	protected string UserFullName = Dimok.User.UserObject.CurrentUserPath;
	public string FilterUser { 
		get {
			EnsureChildControls();
			return ddlUsers.SelectedValue == "" ? UserFullName : ddlUsers.SelectedValue; 
		} 
	}
	bool IsSelfFilter { get { return Profile.UserName.ToLower() == FilterUser.ToLower(); } }
	ProfileCommon FilterProfile { 
		get {
			ProfileCommon pc = IsSelfFilter ? Profile : Profile.GetProfile(FilterUser);
			if (pc.Filters.Filter.PrimaryKey.Length == 0)
				pc.Filters.Filter.PrimaryKey = new DataColumn[] { pc.Filters.Filter.NameColumn, pc.Filters.Filter.PageTypeColumn };
			return pc;
		} 
	}
	string SelectFilterForProfile { get { return SelectFilter.ToUpper().Trim(); } }
	Dimok.ArrayListEx ColumnsTotal = new Dimok.ArrayListEx(new string[] { "amtfin", "balrem", "total principal", "dealer discount", "total payments", "finance charges", "interest income","pastdueamount","resale amt_","bookvaluecurrent" });
	Dimok.ArrayListEx ColumnsAverage = new Dimok.ArrayListEx(new string[] { "dpd", "dslp", "apr", "payment amount", "amtfin", "balrem", "total principal", "dealer discount", "total payments", "finance charges", "interest income", "paymentsbehindm", "gl_days", "pastdueamount", "dpdcalc", "duedatesince", "resale amt_","car year","bookvaluecurrent","pltv" });
	public int LoanID { get { return GridViewEx.SelectedDataKey == null ? 0 : int.Parse("0" + GridViewEx.SelectedDataKey["LoanID"]); } }
	public string VantageID { get { return GridViewEx.SelectedDataKey == null ? "" : GridViewEx.SelectedDataKey["VantageID"] + ""; } }
	private Profiler _profileLib;
	private Profiler profileLib {
		get {
			if (_profileLib != null) return _profileLib;
			return _profileLib = new Profiler(Profile, Page, this);
		}
	}

	private static Dimok.Data.ADsUser.th_AdsUserDataTable _users = null;

	public Dimok.Data.ADsUser.th_AdsUserDataTable GetUsers() {
		if (_users == null) {
			Data.DataSources.UsersDataSource dsoUsers = new Data.DataSources.UsersDataSource();
			dsoUsers.ShowProfiles = true;
			_users = dsoUsers.SelectEx();
		}
		return _users;
	}

	protected override void OnInit(EventArgs e) {
		base.OnInit(e);

		BypassSelectException = true;

		RowSelected += new GridViewExEventHandler(USIXExportList_RowSelected);
		SearchChanged += new SearchChangedEventHandler(USIXExportList_SearchChanged);

		ds.Selected += new ObjectDataSourceStatusEventHandler(ds_Selected);

		btnSaveFilter.Command += new CommandEventHandler(USIXExportList_Command);
		btnDeleteFilter.Command += new CommandEventHandler(USIXExportList_Command);
		btnExcel.Command += new CommandEventHandler(btnExcel_Command);

		grv.SearchChanged += new GridViewEx.SearchChangedEventHandler(grv_SearchChanged);
		grv.DataBound += new EventHandler(grv_DataBound);

		ShowWelcomeLetters.Command += new CommandEventHandler(ShowWelcomeLetters_Command);

		GridViewEx.Sorted += new EventHandler(GridViewEx_Sorted);

		dsUsersCached.TypeName = this.GetType().AssemblyQualifiedName;

		Page.LoadComplete += new EventHandler(Page_LoadComplete);
		ddlFontSize.SelectedIndexChanged += new EventHandler(ddlFontSize_SelectedIndexChanged);

		//NoteTypes.RowInserted += new EventHandler<GridViewInsertEventArgs>(NoteTypes_RowInserted);
		//NoteActionCodes.RowInserted += new EventHandler<GridViewInsertEventArgs>(NoteActionCodes_RowInserted);
		//NoteActionCode_Statuses.RowInserted += new EventHandler<GridViewInsertEventArgs>(NoteActionCode_Statuses_RowInserted);
	}

	void ddlFontSize_SelectedIndexChanged(object sender, EventArgs e) {
		profileLib.Page.FontSize = ((ListControl)sender).SelectedValue;
		profileLib.Save();
	}

	void GridViewEx_Sorted(object sender, EventArgs e) {
		profileLib.Grid.Sort = GridViewEx.SortExpression;
	}

	void Page_LoadComplete(object sender, EventArgs e) {
	}

	void ShowWelcomeLetters_Command(object sender, CommandEventArgs e) {
		string guid = Guid.NewGuid().ToString();
		Cache.Insert(guid, SelectFilter, null, DateTime.Now.AddSeconds(30), System.Web.Caching.Cache.NoSlidingExpiration);
		Response.Redirect("/Manager/Documents/Letter.aspx?Letter="+ddlLetters.SelectedValue+"&Filter="+guid, true);	
		Response.End();
	}

	public bool FieldsChooserMode { get { return chkFieldChooser.Checked; } }
	protected override void OnLoad(EventArgs e) {
		base.OnLoad(e);
		GridViewEx = grv;
		ObjectDS = ds;

		grv.FieldsChooserMode = chkFieldChooser.Checked;
		if (!IsPostBack) {
			JS.ScriptLocalIDs(Page.Form, hdnFilterName, hdnFilterUser, ddlUsers);

			SelectFilter = grv.LastSearch = Filter != "" ? Filter : (uox.UserName.ToLower() != "jonathan" ? profileLib.Grid.Filter+"" : "");
			//if (Filter != "") grv.SelectedIndex = 0;
			
			grv.HideColumns = profileLib.Grid.HideColumns + "";
			GridViewEx.SortExpression = profileLib.Grid.Sort + "";
			ddlFontSize.SelectedValue = profileLib.Page.FontSize + "";
		}
		btnSaveFilter.CommandArgument = (SelectFilter + "").ToUpper();
		pre.InnerHtml += "Environment.UserDomainName:" + Dimok.User.UserObject.CurrentUserDomain;

	}

	protected override void Render(HtmlTextWriter writer) {
		if (grv.AllowPaging) {
			if (ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
				ScriptManager.GetCurrent(Page).RegisterDataItem(CollectionInfo, VantageID + "");
			base.Render(writer);
			return;
		}
		Response.Clear();
		Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
		Response.Charset = "";
		// If you want the option to open the Excel file without saving than
		// comment out the line below
		// Response.Cache.SetCacheability(HttpCacheability.NoCache);
		Response.ContentType = "application/vnd.xls";
		System.IO.StringWriter stringWrite = new System.IO.StringWriter();
		System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
		grv.RenderControl(htmlWrite);
		Response.Write(stringWrite.ToString());
		Response.End();
	}

	void btnExcel_Command(object sender, CommandEventArgs e) {
		grv.RequiresDataBinding = true;
		grv.AllowPaging = false;
		grv.AllowSorting = false;
		grv.ShowSearch = false;
		SetCaption("");
	}

	void grv_SearchChanged(string search) {
		ddlFilters.SelectedValue = ddlFilters.Items.FindByValue(SelectFilterForProfile) == null ? "" : SelectFilterForProfile;
		InitFilter();
	}

	protected void ddlFilters_PreRender(object sender, EventArgs e) {
		try {
			if (ddlFilters.Items.FindByValue(SelectFilterForProfile) != null &&
				ddlFilters.SelectedValue != SelectFilterForProfile)
				ddlFilters.SelectedValue = SelectFilterForProfile;
			if (!IsPostBack) ScriptLocal(sender);
		} catch { }
		if (ddlFilters.SelectedIndex >= 0) btnDeleteFilter.CommandArgument = ddlFilters.SelectedItem.Text;
		btnDeleteFilter.Visible = ddlFilters.SelectedIndex > 1;
	}

	protected void ddlUsers_SelectedIndexChanged(object sender, EventArgs e) {
		ddlFilters.SelectedValue = "";
		ddlFilters.DataBind();
	}

	protected void ddlUsers_DataBound(object sender, EventArgs e) {
		if (!IsPostBack) {
			ddlUsers.SelectedValue = Dimok.User.UserObject.CurrentUserPath.ToLower();
			ScriptLocal(sender);
		}
		pre.InnerHtml += "<br>" + Dimok.User.UserObject.CurrentUserPath.ToLower();
	}

	protected void ddlFilters_SelectedIndexChanged(object sender, EventArgs e) {
		SelectFilter = ddlFilters.SelectedItem.Value.Trim();
		string filterName = ddlFilters.SelectedIndex < 0 ? "" : Regex.Replace(ddlFilters.SelectedItem.Text, @"\{.+\}$", "");
		GridFilterDS.FilterDataTable dtFilter = FilterProfile.Filters.Filter;
		GridFilterDS.FilterRow rowFilter = dtFilter.FindByNamePageType(filterName, PageBase.FilterPageType(this));
		if (rowFilter == null || rowFilter.HideColumns == "")
			rowFilter = Profile.Filters.Filter.FindByNamePageType("", PageBase.FilterPageType(this));
		if (rowFilter != null && rowFilter.HideColumns != "")
			grv.HideColumns = rowFilter.HideColumns;
		SetFilterBoxes(SelectFilter);
		grv.RequiresDataBinding = true;
		SetCaption(SelectFilterForProfile);
		//btnDeleteFilter.Visible = ddlFilters.SelectedIndex > 1;
	}


	protected void USIXExportList_Command(object sender, CommandEventArgs e) {
		GridFilterDS.FilterRow r;
		ProfileCommon p = hdnFilterUser.Value == "" ? FilterProfile : Profile.GetProfile(Lib.GetUserFullName(hdnFilterUser.Value));
		switch (e.CommandName) {
			case "Import":
				Data.SQL.ExecuteSP("usix.s_Export", (e.CommandArgument + "").Split(','));
				break;
			case "SaveFilter":
				//if (p.UserName != Profile.UserName && !uox.IsAdmin) throw new NotSupportedException("Sorry. You are not authorized to save filter for other user.");
				if (hdnFilterName.Value == "null") hdnFilterName.Value = "";
				r = p.Filters.Filter.FindByNamePageType(hdnFilterName.Value,PageBase.FilterPageType(this));
				if (r != null) {
					r.Value = SelectFilterForProfile;
					r.HideColumns = grv.HideColumns;
					r.SortExpression = grv.SortExpression;
				} else p.Filters.Filter.AddFilterRow(hdnFilterName.Value + "", hdnFilterName.Value == "" ? "" : SelectFilterForProfile, grv.HideColumns, grv.SortExpression, Page.GetType().Name);
				p.Filters.AcceptChanges();
				p.Save();
				ddlFilters.DataBind();
				break;
			case "DeleteFilter":
				if (FilterUser.ToLower() != Profile.UserName.ToLower() && !uox.IsAdmin) throw new NotSupportedException("Sorry. " + Profile.UserName + " is not an owner of " + FilterUser + ".");
				r = p.Filters.Filter.FindByNamePageType(e.CommandArgument + "", PageBase.FilterPageType(this));
				if (r != null) {
					r.Delete();
					p.Filters.AcceptChanges();
					p.Save();
					ddlFilters.ClearSelection();
					ddlFilters.DataBind();
				}
				break;
			//System.Collections.Generic.List<string> list = new System.Collections.Generic.List<string>(Profile.Filters);
			//if( .Contains(SelectFilter)){
			//  Profile.Filters
			default: throw new NotImplementedException(e.CommandName + " is not implemented");
		}
	}

	void grv_DataBound(object sender, EventArgs e) {
		//CollectionInfo.UpdateParameters();
	}
	bool SyntaxError = false;
	protected void ds_Selected(object sender, ObjectDataSourceStatusEventArgs e) {
		if (e.Exception != null) {
			TargetInvocationException tie = e.Exception as TargetInvocationException;
			if (tie == null) return;
			System.Data.SqlClient.SqlException excSQL = tie.InnerException as System.Data.SqlClient.SqlException;
			if (excSQL != null && new int[]{102,207}.Contains(excSQL.Number) && !SyntaxError) {
				e.ExceptionHandled = true;
				SyntaxError = true;
				profileLib.Grid.Sort = "";
				profileLib.Grid.Filter = "";
				profileLib.Grid.HideColumns = "";
				profileLib.Save();
				Profile.Save();
				//Response.End();
				//return;
				ds.Where.Clear();
				GridViewEx.RequiresDataBinding = true;
				return;
			}
			e.ExceptionHandled = true;
			profileLib.Grid.Sort = "";
			profileLib.Grid.Filter = "";
			profileLib.Grid.HideColumns = "";
			profileLib.Save();
			Profile.Save();
			Dimok.Exceptions.ASPException.Publish(tie.InnerException);
			return;
		}
		if( !SyntaxError) InitFilter();
		Dimok.Common.TraceMe("");
		System.Data.DataView dv = e.ReturnValue as System.Data.DataView;
		if (dv != null && dv.Count == 1 && dv[0][0] != DBNull.Value)
			grv.SelectedIndex = 0;
		if (dv == null || dv.Count < 2) return;
		grv.HeaderTotals = dv.Table.Clone();
		System.Data.DataRow rowSum = grv.HeaderTotals.NewRow();
		foreach (System.Data.DataColumn column in dv.Table.Columns)
			rowSum[column.ColumnName] = ColumnsTotal.Contains(column.ColumnName.ToLower()) ?
				string.Format("{0:n}", GridViewEx.GetColumnTotal(dv.Table.Rows, column.ColumnName)) : " ";
		System.Data.DataRow rowAvg = grv.HeaderTotals.NewRow();
		foreach (System.Data.DataColumn column in dv.Table.Columns)
			rowAvg[column.ColumnName] = ColumnsAverage.Contains(column.ColumnName.ToLower()) ?
				string.Format("{0:n" + (dv.Table.Columns[column.ColumnName].DataType == typeof(decimal) ? "1" : "0") + "}", GridViewEx.GetColumnAverage(dv.Table.Rows, column.ColumnName)) : " ";
		grv.HeaderTotals.Rows.InsertAt(rowSum, 0);
		grv.HeaderTotals.Rows.InsertAt(rowAvg, 1);
	}
	object GetColumnTotal(System.Data.DataRowCollection rows, string column) {
		decimal dd = 0;
		foreach (System.Data.DataRow row in rows) {
			if (row[column] == DBNull.Value) continue;
			decimal d;
			if (!decimal.TryParse(row[column] + "", out d)) return DBNull.Value;
			dd += d;
		}
		return dd != 0 ? (object)dd : (object)DBNull.Value;
	}
	object GetColumnAverage(System.Data.DataRowCollection rows, string column) {
		decimal dd = 0, count = 0;
		foreach (System.Data.DataRow row in rows) {
			if (row[column] == DBNull.Value) continue;
			decimal d;
			if (!decimal.TryParse(row[column] + "", out d)) return DBNull.Value;
			dd += d;
			count++;
		}
		return dd != 0 ? (object)(Math.Round(dd / count, 2)) : (object)DBNull.Value;
	}
	protected void USIXExportList_SearchChanged(string search) {
		InitDetails();
	}

	protected void USIXExportList_RowSelected(object sender, GridViewExEventArgs e) {
		InitDetails();
	}
	void InitFilter() {
		profileLib.Grid.Filter = SelectFilterForProfile;
		profileLib.Grid.HideColumns = grv.HideColumns;
		SetCaption(SelectFilterForProfile);
	}
	protected void InitDetails() {
		//grvComments.SetFilterBoxes(null);
		//grvPayments.SetFilterBoxes(null);
	}
	void SetCaption(string Caption) {
		lblCaption.Text = Caption;
	}
	protected string ShowApplicantJS(object applID) { return "event.cancelBubble = true;if(!event.ctrlKey)showApplInfo(" + applID + ")"; }
}
